#!/bin/bash

rm -rf ./tmp/
mkdir ./tmp/

### Build gateway

cd ./demo-gateway/
chmod +x gradlew
./gradlew clean bootJar
cp ./build/libs/demo-gateway-0.0.1-SNAPSHOT.jar ../ansible-playbooks/roles/java-application/files/
cd ..

### Build service

cd ./demo-service/
chmod +x gradlew
./gradlew clean bootJar
cp ./build/libs/demo-service-0.0.1-SNAPSHOT.jar ../ansible-playbooks/roles/java-application/files/
cd ..

### Start VM environment

cd vagrant
vagrant up
bash ./gather-inventory.sh
python3 build-ansible-inventory.py
cp -f ./inventory.ini ../ansible-playbooks/inventory.ini

cd ..

### Deploy components with ansible

cd ansible-playbooks
ansible-playbook consul-cluster-playbook.yaml

cd ../vagrant
vagrant scp ../consul-configurations/acl consul-1:~/
vagrant ssh consul-1 -c "bash ~/acl/initialize-acl.sh"

vagrant scp consul-1:~/acl/*.token ../tmp/

TOKEN_SERVICE=$(cat ../tmp/srv.token)
TOKEN_GATEWAY=$(cat ../tmp/gateway.token)
TOKEN_GATEWAY_ISOLATED=$(cat ../tmp/gateway-isolated.token)
TOKEN_LOADBALANCER=$(cat ../tmp/loadbalancer.token)

cd ../ansible-playbooks

ansible-playbook service-playbook.yaml --extra-vars "consul_client_acl_token=$TOKEN_SERVICE"
ansible-playbook gateway-playbook.yaml --extra-vars "consul_client_acl_token=$TOKEN_GATEWAY"
ansible-playbook lb-playbook.yaml --extra-vars "consul_client_acl_token=$TOKEN_LOADBALANCER"

# can't be executed here,
# currently, autogenerated inventory file is not supported  [isolated-gw] group
# which required for isolated-gw
# ansible-playbook gateway-playbook-isolated-gw.yaml --extra-vars "consul_client_acl_token=$TOKEN_GATEWAY_ISOLATED"

cd ..

### Done

echo "######### Done #########"
cat ansible-playbooks/inventory.ini
